import tracker from '../utils/tracker'
import onload from '../utils/onload'
import getSelector from '../utils/getLastSelector'
import getLastEvent from '../utils/getLastEvent'

export function timming() {
  onload(function () {
    let FMP, LCP
    new PerformanceObserver((entryList, observer) => {
      let perfEntries = entryList.getEntries()
      FMP = perfEntries[0]
      observer.disconnect() //结束观察
    }).observe({ entryTypes: ['element'] }) //观察页面中有意义的元素

    new PerformanceObserver((entryList, observer) => {
      let perfEntries = entryList.getEntries()
      LCP = perfEntries[0]
      observer.disconnect() //结束观察
    }).observe({ entryTypes: ['largest-contentful-paint'] }) //观察页面中最大的元素

    new PerformanceObserver((entryList, observer) => {
      let lastEvent = getLastEvent()
      let firstInupt = entryList.getEntries()[0]
      if (firstInupt) {
        //开始处理的时间-点击的时间 ，差值就是处理的延迟
        let inputDelay = firstInupt.processingStart - firstInupt.startTime + ''
        let duration = firstInupt.duration + '' //处理的时间
        if (inputDelay > 0 || duration > 0) {
          tracker.send({
            kind: 'experience', //用户体验指标
            type: 'firstInputDelay', //首次输入延迟
            inputDelay,
            duration,
            startTime: firstInupt.startTime + '',
            selector: lastEvent
              ? getSelector(lastEvent.path || lastEvent.target)
              : '',
          })
        }
      }
      observer.disconnect() //结束观察
    }).observe({ type: 'first-input', buffered: true }) //观察用户交互延迟

    let navTime = performance.getEntriesByType('navigation')[0]
    setTimeout(() => {
      const {
        fetchStart,
        connectStart,
        connectEnd,
        requestStart,
        responseStart,
        responseEnd,
        domInteractive,
        domContentLoadedEventStart,
        domContentLoadedEventEnd,
        loadEventStart,
      } = navTime
      tracker.send({
        kind: 'experience', //用户体验指标
        type: 'timing', //统计每个阶段的时间
        connectTime: connectEnd - connectStart + '', //连接时间
        ttft: responseStart - requestStart + '', //首字节到达时间
        responseTime: responseEnd - responseStart + '', //相应的读取时间
        parseDOMTime: loadEventStart - domInteractive + '', //解析dom的时间
        domContentLoadEventTime:
          domContentLoadedEventEnd - domContentLoadedEventStart + '',
        timeToInteractive: domInteractive - fetchStart + '', //首次可交互时间
        loadTime: loadEventStart - fetchStart + '', //完整的加载时间
      })

      let FP = performance.getEntriesByName('first-paint')[0] //首次绘制
      let FCP = performance.getEntriesByName('first-contentful-paint')[0] //首次内容绘制

      //开始发送性能指标
      tracker.send({
        kind: 'experience', //用户体验指标
        type: 'timing', //统计每个阶段的时间
        firstPaint: FP.startTime + '',
        firstContentPaint: FCP.startTime + '',
        firstMeaningfulPaint: FMP.startTime + '',
        largestContentPaint: LCP.startTime + '',
      })
    }, 3000)
  })
}
